﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MVC4App.Areas.Auth.Models;
using MVC4App.Code;
using MVC4App.Filters;
using MVC4App.Repositories.Core;
using MVC4App.Repositories.Implementations;
using MVC4App.SecurityServiceReference;

namespace MVC4App.Areas.Auth.Controllers
{
    [AllowAnonymous]
    [InitializeSimpleMembership]
    public class AuthController : Controller
    {
        private readonly IAuthRepository _authRepository;
        /// <summary>
        /// Default Constructor for AuthController.
        /// </summary>
        public AuthController() :
            this(new AuthRepository())
        {                    }

        /// <summary>
        /// Overloaded 'injectable' Constructor for AuthController.
        ///
        /// Pattern: Constructor Dependency Injection (DI).
        /// </summary>
        /// <param name="authRepository">The authentication repository</param>
        public AuthController(IAuthRepository authRepository)
        {
            _authRepository = authRepository;
        }
        //
        // GET: /Administrators/Auth/

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            var message = string.Empty;
            //Roles.CreateRole("Administrators");
            //Roles.AddUserToRole("sa", "Administrators");
            //WebSecurity.CreateUserAndAccount("sa", "123123", false);
            if (ModelState.IsValid)
            {
                var response = _authRepository.Login(model.UserName, model.Password);
                if (response.Acknowledge.Equals(AcknowledgeType.Success))
                {
                    Session["UserId"] = response.UserId;
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    if (!string.IsNullOrEmpty(returnUrl))
                        return Redirect(returnUrl);
                    return RedirectToAction("Index", "Admin", new { area = "Administrators" });
                }
                message = response.Message;
            }
            ModelState.AddModelError("", message);
            return View(model);
        }
        public ActionResult Logout()
        {
            _authRepository.Logout();
            FormsAuthentication.SignOut();
            return Redirect(UrlMaker.ToLogin());
        }

    }
}
